<template>
  <div class="admin-layout">
    <AdminHeader />
    <div class="main-wrapper">
      <AdminNavbar />
      <div class="content-wrapper">
        <div class="free-line-container">
          <div class="page-header">
            <h2>订单分配</h2>
            <div class="header-actions">
              <el-button type="primary" @click="refreshData">
                <el-icon><Refresh /></el-icon> 刷新数据
              </el-button>
            </div>
          </div>

          <el-alert
            v-if="showTip"
            title="提示：拖拽生产线到订单进行分配，只有产品型号匹配的生产线才能分配成功"
            type="info"
            :closable="false"
            show-icon
            style="margin-bottom: 20px"
          />

          <div class="drag-container">
            <!-- 左侧：空闲订单列表 -->
            <div class="orders-panel">
              <div class="panel-header">
                <h3>待分配订单</h3>
                <el-input
                  v-model="orderSearchKeyword"
                  placeholder="搜索订单"
                  clearable
                  class="search-input"
                  @clear="handleOrderSearch"
                  @keyup.enter="handleOrderSearch"
                >
                  <template #suffix>
                    <el-icon class="el-input__icon" @click="handleOrderSearch">
                      <Search />
                    </el-icon>
                  </template>
                </el-input>
              </div>
              <div class="panel-content" v-loading="ordersLoading">
                <div
                  v-if="filteredOrders.length === 0"
                  class="empty-placeholder"
                >
                  暂无待分配订单
                </div>
                <div
                  v-for="order in filteredOrders"
                  :key="order.orderId"
                  class="order-card"
                  :class="{ 'drop-target': isDropTarget(order) }"
                  @dragover.prevent="handleDragOver(order, $event)"
                  @dragleave.prevent="handleDragLeave(order)"
                  @drop.prevent="handleDrop(order, $event)"
                >
                  <div class="order-header">
                    <span class="order-number">订单号: {{ order.orderId }}</span>
                    <el-tag size="small" type="info">{{ order.status }}</el-tag>
                  </div>
                  <div class="order-info">
                    <div class="info-item">
                      <span class="label">产品型号:</span>
                      <span class="value highlight">{{ order.productModel }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">需生产数量:</span>
                      <span class="value">{{ order.quantity }}</span>
                        <span class="label">|</span>
                        <span class="label">色温参数:</span>
                        <span class="value">{{ order.colorTemp }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">客户:</span>
                      <span class="value">{{ order.customer }}</span>
                        <span class="label"></span>
                        <span class="label">联系方式:</span>
                        <span class="value">{{ order.customerPhone }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">交付日期:</span>
                      <span class="value">{{ formatDate(order.endtime) }}</span>
                        <span class="label">|</span>
                        <span class="label">订单已生产:</span>
                        <span class="value">{{ order.count }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 右侧：空闲生产线列表 -->
            <div class="lines-panel">
              <div class="panel-header">
                <h3>空闲生产线</h3>
                <el-input
                  v-model="lineSearchKeyword"
                  placeholder="搜索生产线"
                  clearable
                  class="search-input"
                  @clear="handleLineSearch"
                  @keyup.enter="handleLineSearch"
                >
                  <template #suffix>
                    <el-icon class="el-input__icon" @click="handleLineSearch">
                      <Search />
                    </el-icon>
                  </template>
                </el-input>
              </div>
              <div class="panel-content" v-loading="linesLoading">
                <div
                  v-if="filteredLines.length === 0"
                  class="empty-placeholder"
                >
                  暂无空闲生产线
                </div>
                <div
                  v-for="line in filteredLines"
                  :key="line.lineId"
                  class="line-card"
                  draggable="true"
                  @dragstart="handleDragStart(line, $event)"
                  @dragend="handleDragEnd"
                >
                  <div class="line-header">
                    <span class="line-id">生产线 #{{ line.lineId }}</span>
                    <el-tag size="small" type="success">{{ line.status }}</el-tag>
                  </div>
                  <div class="line-info">
                    <div class="info-item">
                      <span class="label">产品型号:</span>
                      <span class="value highlight">{{ line.productModel || '未指定' }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">创建时间:</span>
                      <span class="value">{{ formatDate(line.createdAt) }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分配确认对话框 -->
    <el-dialog
      v-model="assignDialogVisible"
      title="确认分配"
      width="400px"
    >
      <div v-if="currentOrder && currentLine" class="assign-confirm">
        <p>确定要将 <strong>生产线 #{{ currentLine.lineId }}</strong> 分配给 <strong>订单 {{ currentOrder.orderNumber }}</strong> 吗？</p>

        <div class="confirm-details">
          <div class="detail-item">
            <span class="label">订单产品型号:</span>
            <span class="value">{{ currentOrder.productModel }}</span>
          </div>
          <div class="detail-item">
            <span class="label">生产线产品型号:</span>
            <span class="value">{{ currentLine.productModel || '未指定' }}</span>
          </div>
          <div class="detail-item">
            <span class="label">开始时间:</span>
            <span class="value">{{ formatDateTime(assignForm.startTime) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">预计结束时间:</span>
            <span class="value">{{ formatDateTime(assignForm.endTime) }}</span>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAssign">确认分配</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import AdminHeader from '@/components/AdminHeader.vue'
import AdminNavbar from '@/components/AdminNavbar.vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getFreeOrders, getFreeProductionLine, assignOrderToLine } from '@/api/production'

// 数据定义
const orders = ref([])
const lines = ref([])
const ordersLoading = ref(false)
const linesLoading = ref(false)
const orderSearchKeyword = ref('')
const lineSearchKeyword = ref('')
const showTip = ref(true)
const assignDialogVisible = ref(false)
const currentOrder = ref(null)
const currentLine = ref(null)
const dropTargetId = ref(null)

// 分配表单数据
const assignForm = ref({
  startTime: new Date(),
  endTime: new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000) // 默认一周后
})

// 过滤后的订单列表
const filteredOrders = computed(() => {
  if (!orderSearchKeyword.value) return orders.value

  const keyword = orderSearchKeyword.value.toLowerCase()
  return orders.value.filter(order =>
    order.orderNumber.toLowerCase().includes(keyword) ||
    order.productModel.toLowerCase().includes(keyword) ||
    order.customerName.toLowerCase().includes(keyword)
  )
})

// 过滤后的生产线列表
const filteredLines = computed(() => {
  if (!lineSearchKeyword.value) return lines.value

  const keyword = lineSearchKeyword.value.toLowerCase()
  return lines.value.filter(line =>
    (line.productModel && line.productModel.toLowerCase().includes(keyword)) ||
    line.lineId.toString().includes(keyword)
  )
})

// 获取空闲订单列表
const fetchOrders = async () => {
  ordersLoading.value = true
  try {
    const res = await getFreeOrders()
    if (res.success) {
      orders.value = res.data || []
    } else {
      ElMessage.error(res.message || '获取空闲订单列表失败')
    }
  } catch (error) {
    ElMessage.error('获取空闲订单列表失败')
    // 模拟数据，实际项目中应删除
  } finally {
    ordersLoading.value = false
  }
}

// 获取空闲生产线列表
const fetchLines = async () => {
  linesLoading.value = true
  try {
    const res = await getFreeProductionLine()
    if (res.success) {
      lines.value = res.data || []
    } else {
      ElMessage.error(res.message || '获取空闲生产线列表失败')
    }
  } catch (error) {
    ElMessage.error('获取空闲生产线列表失败')
    // 模拟数据，实际项目中应删除
  } finally {
    linesLoading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  fetchOrders()
  fetchLines()
}

// 搜索处理
const handleOrderSearch = () => {
  // 过滤由计算属性处理
}

const handleLineSearch = () => {
  // 过滤由计算属性处理
}

// 拖拽处理
const handleDragStart = (line, event) => {
  currentLine.value = line
  event.dataTransfer.setData('text/plain', line.lineId)
  event.dataTransfer.effectAllowed = 'move'
}

const handleDragEnd = () => {
  // 拖拽结束，清除所有拖拽状态
  dropTargetId.value = null
}

const handleDragOver = (order, event) => {
  // 检查产品型号是否匹配
  if (isProductModelMatched(order, currentLine.value)) {
    event.dataTransfer.dropEffect = 'move'
    dropTargetId.value = order.orderId
  } else {
    event.dataTransfer.dropEffect = 'none'
  }
}

const handleDragLeave = () => {
  dropTargetId.value = null
}

const handleDrop = (order, event) => {
  const lineId = event.dataTransfer.getData('text/plain')
  dropTargetId.value = null

  // 检查产品型号是否匹配
  if (!isProductModelMatched(order, currentLine.value)) {
    ElMessage.warning('产品型号不匹配，无法分配')
    return
  }

  // 设置当前订单和打开确认对话框
  currentOrder.value = order
  assignForm.value.startTime = new Date()
  assignForm.value.endTime = new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000) // 默认一周后
  assignDialogVisible.value = true
}

// 检查产品型号是否匹配
const isProductModelMatched = (order, line) => {
  // 如果生产线没有指定产品型号，则可以分配任何订单
  if (!line.productModel) return true

  // 否则产品型号必须匹配
  return order.productModel === line.productModel
}

// 判断是否是当前拖拽目标
const isDropTarget = (order) => {
  return dropTargetId.value === order.orderId
}

// 确认分配
const confirmAssign = async () => {
  if (!currentOrder.value || !currentLine.value) return

  try {
    const res = await assignOrderToLine(currentOrder.value.orderId, currentLine.value.lineId)
    if (res.success) {
      ElMessage.success('订单分配成功')
      assignDialogVisible.value = false
      refreshData() // 刷新数据
    } else {
      ElMessage.error(res.errorMsg || '订单分配失败')
    }
  } catch (error) {
      assignDialogVisible.value = false
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${formatDate(dateStr)} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 组件挂载时获取数据
onMounted(() => {
  refreshData()
})
</script>

<style scoped>
.admin-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7f9;
}

.main-wrapper {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.content-wrapper {
  flex: 1;
  padding: 24px;
  overflow: auto;
  background: #fff;
  margin: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.free-line-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.drag-container {
  display: flex;
  gap: 20px;
  height: calc(100vh - 250px);
}

.orders-panel,
.lines-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.panel-header {
  padding: 15px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.search-input {
  width: 200px;
}

.panel-content {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background-color: #f9fafc;
}

.empty-placeholder {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #909399;
  font-size: 14px;
}

.order-card,
.line-card {
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.line-card {
  cursor: move;
}

.line-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.1);
}

.order-card.drop-target {
  border: 2px dashed #409eff;
  background-color: rgba(64, 158, 255, 0.1);
}

.order-header,
.line-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.order-number,
.line-id {
  font-weight: bold;
  font-size: 15px;
}

.order-info,
.line-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item {
  display: flex;
  align-items: center;
}

.label {
  color: #606266;
  margin-right: 8px;
  min-width: 80px;
}

.value {
  color: #303133;
}

.value.highlight {
  color: #409eff;
  font-weight: bold;
}

.assign-confirm {
  text-align: center;
}

.confirm-details {
  margin-top: 20px;
  text-align: left;
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.detail-item {
  margin-bottom: 10px;
  display: flex;
}

.detail-item .label {
  color: #606266;
  min-width: 120px;
}

.detail-item .value {
  color: #303133;
  font-weight: bold;
}
</style>
